/*
@hehung
2023-2-8
转载请注明出处，版权由@hehung所有
email: 1398660197@qq.com
wechat: hehung95
*/

// MQ5 - 可燃气体传感器，用来检测可燃气体，使用的是ADC获取空气中可燃气体浓度
// P000 ADC0 CH0

#include "hal_data.h"
#include "app_mq5.h"


#define MQ5_DEBUG
#undef MQ5_DEBUG

#ifdef MQ5_DEBUG
#include <stdio.h>
#define LOG(fmt, ...) 	          printf(fmt, ##__VA_ARGS__)
#else
#define LOG(fmt, ...)
#endif


// adc sampling resoultion is 12bits
#define MQ5_ADC_RESOLUTION            (12U)
#define MQ5_ADC_MAX_VALUE             (4095)

#define MQ5_ADC_CHANNEL               (0U)
#define MQ5_MAX_VALUE                 (10000U)   //ppm
#define MQ5_MIN_VALUE                 (300U)     //ppm


// Value for Combustible gas concentration
static uint32_t mq5_val_ppm = 0U;


static void Mq5_DataConvert(uint16_t adc_data);


// Convert the ADC value to percent value
static void Mq5_DataConvert(uint16_t adc_data)
{
    // calculate the Combustible gas simple in ppm, it is not an accurate actual value
    // y = kx+b, x = 0, y = 300, x = 4095, y = 10000, so k = (10000-300)/4095
    mq5_val_ppm = ((MQ5_MAX_VALUE - MQ5_MIN_VALUE) / MQ5_ADC_MAX_VALUE) * adc_data;
}


// Initialize the MQ5 - ADC0 CH0 P000
void Mq5_Init(void)
{
    fsp_err_t err = FSP_SUCCESS;
	
    /* Initializes the adc. */
    err = R_ADC_Open(&g_adc0_ctrl, &g_adc0_cfg);
	/* Handle any errors. This function should be defined by the user. */
    assert(FSP_SUCCESS == err);
    /* Enable channels. */
    err = R_ADC_ScanCfg(&g_adc0_ctrl, &g_adc0_channel_cfg);
    assert(FSP_SUCCESS == err);

    /* Enable scan triggering from ELC events. */
    (void)R_ADC_ScanStart(&g_adc0_ctrl);
}


// Read conversion result 
void Mq5_RunningEntry(void)
{	
	fsp_err_t err = FSP_SUCCESS;
	uint16_t adc_value;
	
	err = R_ADC_Read(&g_adc0_ctrl, MQ5_ADC_CHANNEL, &adc_value);
    if (FSP_SUCCESS == err)
	{
        LOG ("Mq5: Read value: %d: %d\n", MQ5_ADC_CHANNEL, adc_value);
    }
    else
    {
        LOG ("MQ5: Read MQ5 Data Error\n");
    }

    Mq5_DataConvert(adc_value);
}

// get the value and the unit is ppm
uint32_t Mq5_GetGasPpmValue(void)
{
    return mq5_val_ppm;
}

